package com.netty.netty.high.demo1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {

  private static final Logger log= LoggerFactory.getLogger(NettyClient.class);

  public static void main(String[] args) {

    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    ChannelFuture channelFuture = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<Channel>() {
              @Override
              protected void initChannel(Channel ch) throws Exception {

                //不进行加解密不然展示不出粘包效果
//                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(new LoggingHandler());



              }
            }).connect("localhost", 8080);

    channelFuture.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {

        Channel channel = future.channel();

        ByteBuf byteBuf = channel.alloc().buffer(16);
        for (int i=0;i<10;i++){
          byteBuf.retain();
          byteBuf.writeBytes(("hello").getBytes("utf-8"));
          channel.writeAndFlush(byteBuf);
          byteBuf.clear();
        }

        channel.close();

        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            eventLoopGroup.shutdownGracefully();
          }
        });
      }
    });

  }
}
